# Makefile for the JSON-RPC Project (Corrected)

# Compiler and flags
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -Wpedantic -I./lib -I./common -g 
LDFLAGS =

# Directories
SRC_DIR_COMMON = common
SRC_DIR_SERVER = server
SRC_DIR_CLIENT = client
LIB_DIR = lib
BUILD_DIR = build

# Source files
COMMON_SRCS = $(SRC_DIR_COMMON)/rpc_protocol.c
LIB_SRCS = $(LIB_DIR)/cJSON.c
SERVER_SRCS = $(SRC_DIR_SERVER)/server.c $(SRC_DIR_SERVER)/remote_functions.c $(COMMON_SRCS) $(LIB_SRCS)
CLIENT_SRCS = $(SRC_DIR_CLIENT)/client.c $(COMMON_SRCS) $(LIB_SRCS)

# Object files from source files
SERVER_OBJS = $(patsubst %.c, $(BUILD_DIR)/%.o, $(SERVER_SRCS))
CLIENT_OBJS = $(patsubst %.c, $(BUILD_DIR)/%.o, $(CLIENT_SRCS))

# --- FIX IS HERE ---
# Executable targets are now placed directly in the build directory
# to avoid name conflicts with subdirectories.
SERVER_EXE = $(BUILD_DIR)/rpc_server
CLIENT_EXE = $(BUILD_DIR)/rpc_client

# Phony targets
.PHONY: all clean

# Default target
all: $(SERVER_EXE) $(CLIENT_EXE)

# Rule to build the server executable
$(SERVER_EXE): $(SERVER_OBJS)
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)
	@echo "Built server executable: $@"

# Rule to build the client executable
$(CLIENT_EXE): $(CLIENT_OBJS)
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)
	@echo "Built client executable: $@"

# Generic rule to compile .c source files to .o object files
# It creates the necessary build subdirectories automatically.
$(BUILD_DIR)/%.o: %.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) -c $< -o $@

# Clean up build artifacts
clean:
	rm -rf $(BUILD_DIR)
	@echo "Cleaned build directory."
